package com.imau.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.imau.bean.User;
import com.imau.common.entiry.ProfileResult;
import com.imau.common.entiry.ResultCode;
import com.imau.common.exception.CommonException;
import com.imau.common.utils.TokenUtil;
import com.imau.service.UserService;
import com.imau.service.impl.UserServiceImpl;
import com.mysql.cj.util.StringUtils;
import io.jsonwebtoken.Claims;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "UserController", value = "/user/*")
public class UserController extends Baseconterllor {


    private UserService userService = new UserServiceImpl();


    /**
     * 添加教师
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



        //前端JSON对象
        String jsonString = request.getReader().readLine();

        //转成对象
        User User = JSON.parseObject(jsonString, User.class);

        //3.保存
        User entiry = userService.save(User);

        //4.返回响应

        this.writeResult(response, entiry == null ? false : true);


    }


    /**
     * 删除
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void removeById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //前端JSON对象
        String id = request.getParameter("id");


        //删除
        int row = userService.deleteById(id);
        //4.返回响应

        this.writeResult(response, row > 0 ? true : false);


    }


    protected void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //前端JSON对象
        String jsonString = request.getReader().readLine();

        //转成对象
        User user = JSON.parseObject(jsonString, User.class);

        //3.保存
        int row = userService.updateUser(user);

        //4.返回响应

        this.writeResult(response, row > 0 ? true : false);


    }


    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //前端JSON对象
        String jsonString = request.getReader().readLine();
        User user = null;
        //转成对象
        if (!StringUtils.isNullOrEmpty(jsonString)) {
            user = JSON.parseObject(jsonString, User.class);

        }

        String currentPage = request.getParameter("currentPage");

        String pageSize = request.getParameter("pageSize");

        //3.保存

        PageInfo<User> pageInfo = userService.queryListByPagte(user, Integer.valueOf(currentPage), Integer.valueOf(pageSize));

        //4.返回响应
        writeResultAndData(response, pageInfo);


    }


    protected void getInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        String id = request.getParameter("id");


        User User = userService.findById(id);

        //4.返回响应
        writeResultAndData(response, User);


    }

    /**
     * 分配角色
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */

    protected void assignRoles(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.用户的Id主键

        String id = request.getParameter("id");

        //2.获取角色的集合
        String jsonRids = request.getReader().readLine();

        String[] rids = JSON.parseObject(jsonRids, String[].class);

        //3. 分配角色
        int row = userService.assignRoles(id, rids);


        //4.返回响应

        this.writeResult(response, row > 0 ? true : false);


    }

    /**
     * 登录请求
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //前端JSON对象 用户名和密码 现在约定是手机号登录
        String jsonString = request.getReader().readLine();

        //转成对象
        User user = JSON.parseObject(jsonString, User.class);
        //1.先按照手机号或是登录账号查询用户
        User user2 = userService.findByField(new User(user.getMobile()));
        //如果用户不存在或密码错误，反馈前端信息
        if (user2 == null || !user2.getPassword().equals(user.getPassword())) {


            this.writeResult(response, ResultCode.UNMOBILEORPASSWORD);

        }else{

//            String token = JwtUtil.createJWT(user2.getId(), user2.getUsername(), new HashMap<>());
            Map<String, Object> map = new HashMap<>();
            map.put("uid",user2.getId());
            map.put("userName",user2.getUsername());

            String token = TokenUtil.genAccessToken(map);

            //2. 响应结果

            this.writeResultAndData(response, token);

        }



    }

    /**
     * 获取个人信息
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void profile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CommonException {


        //请求中获取key为Authorization的头信息
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isNullOrEmpty(authorization)) {
            throw new CommonException(ResultCode.UNAUTHENTICATED);

        }
        //前后端约定头信息内容以 Bearer+空格+token 形式组成
        String token = authorization.replace("Bearer ", "");

        if(TokenUtil.isTokenExpired(token))
        {
            throw new CommonException(ResultCode.UNLOGINEXPIRE);
        }

        //比较并获取claims
        Claims claims = TokenUtil.parsePayload(token);



        if (claims == null) {
            throw new CommonException(ResultCode.UNAUTHENTICATED);
        }





        String userId = claims.get("uid",String.class);

        User user = userService.findById(userId);

        this.writeResultAndData(response, new ProfileResult(user));

    }

}
